package com.pay.core;

import com.alibaba.fastjson.JSONObject;
import com.pay.dao.entity.UserInfo;
import com.pay.service.TokenUntil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * app权限拦截
 * @Description:
 * yinhuachang
 */
@Component
public class SecurityInterceptor implements HandlerInterceptor {

@Autowired
private TokenUntil tokenUntil;

	/**
	 * 完成页面的render后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
                                Exception exception) throws Exception {

	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
                           ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在调用controller具体方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = requestUri.substring(contextPath.length());
		System.out.println("url-->"+url);
		//判断是否包含在菜单权限里 免拦截
		if (url != null && ((url.indexOf("/login") > -1)
				|| url.contains("/sendPic")
				|| url.contains("/downLogInfo")
				)) {
			return true;
		}
		//大屏登入 新增甘泉大屏录入
		if(url.contains("/api/") ){
			String token =request.getHeader("token");
			System.out.println("token1-->"+token);
			if(StringUtils.isBlank(token)){
				outPrint(response,"您还没有登录或登录已超时，请重新登录");
				return false;
			}
			UserInfo sysUser = tokenUntil.getUserbyToken(request);
			if(sysUser==null){
				outPrint(response,"您还没有登录或登录已超时，请重新登录！");
				return false;
			}
		}
		return true;
	}

	public void outPrint(HttpServletResponse response, String msg) throws IOException {
		Map<String,String> outMap = new HashMap<>();
		outMap.put("status","-1");
		outMap.put("msg",msg);
		outMap.put("data","");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(JSONObject.toJSONString(outMap));
	}
	public void outPrint1(HttpServletResponse response, String msg) throws IOException {
		Map<String,String> outMap = new HashMap<>();
		outMap.put("status","1");
		outMap.put("msg",msg);
		outMap.put("data","");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(JSONObject.toJSONString(outMap));
	}
}

